package com.hp.team.bookstore.service.catalog;

import java.io.File;
import java.io.FileInputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hp.team.bookstore.dbaccess.dao.catalog.ProductHibernateDAO;
import com.hp.team.bookstore.model.catalog.Product;

@Service
public class ProductService {

	private static final String IMAGE_UPLOAD_DIR = "C:\\Users\\azmyabda\\Desktop\\Team Goals\\TestImage\\";

	@Autowired
	private ProductHibernateDAO productDAO;

	@Transactional
	public List<Product> getAllProducts() {
		return productDAO.findAll();
	}

	@Transactional
	public Product getProduct(long id) {
		return productDAO.findById(id, false);
	}

	@Transactional
	public Product addProduct(String name, String description, String author, String publisher, String isbn,
			String imagePath) {

		File file = new File(IMAGE_UPLOAD_DIR + imagePath);
		byte[] imageBytes = new byte[(int) file.length()];

		try {
			FileInputStream fileInputStream = new FileInputStream(file);
			// convert file into array of bytes
			fileInputStream.read(imageBytes);
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		Product product = new Product();
		product.setName(name);
		product.setDescription(description);
		product.setAuthor(author);
		product.setPublisher(publisher);
		product.setIsbn(isbn);
		product.setImage(imageBytes);

		// productDAO.setSession(HibernateUtil.getSessionFactory().getCurrentSession());
		// HibernateUtil.beginWriteTransaction();
		productDAO.makePersistent(product);
		// HibernateUtil.commitTransaction();

		return product;
	}
}
